<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态和权限
check_login();
if ($_SESSION['role'] != 1) {
    header("Location: index.php");
    exit();
}

$error = '';
$success = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = safe_input($_POST['username']);
    $password = $_POST['password'];
    $name = safe_input($_POST['name']);
    $phone = safe_input($_POST['phone']);
    $email = safe_input($_POST['email']);
    $role = intval($_POST['role']);
    $status = intval($_POST['status']);
    
    // 验证表单数据
    if (empty($username) || empty($password) || empty($name)) {
        $error = '用户名、密码和姓名不能为空';
    } elseif (strlen($password) < 6) {
        $error = '密码长度不能少于6位';
    } elseif (!empty($phone) && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
        $error = '手机号格式不正确';
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } else {
        try {
            $db = db_connect();
            
            // 检查用户名是否已存在
            $stmt = $db->prepare("SELECT COUNT(*) FROM admin_users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetchColumn() > 0) {
                $error = '用户名已存在';
            } else {
                // 处理头像上传
                $avatar = '';
                if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
                    $filename = $_FILES['avatar']['name'];
                    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                    
                    if (!in_array($ext, $allowed)) {
                        $error = '只允许上传 jpg, jpeg, png, gif 格式的图片';
                    } else {
                        $upload_dir = '../api/user/uploads/avatars/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0777, true);
                        }
                        
                        $new_filename = date('Ymd_His') . '_' . substr(md5(uniqid()), 0, 16) . '.' . $ext;
                        if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_dir . $new_filename)) {
                            $avatar = 'uploads/avatars/' . $new_filename;
                        }
                    }
                }
                
                if (empty($error)) {
                    // 插入新管理员
                    $stmt = $db->prepare("INSERT INTO admin_users (username, password, name, avatar, role, status, phone, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $username,
                        password_hash($password, PASSWORD_DEFAULT),
                        $name,
                        $avatar,
                        $role,
                        $status,
                        $phone,
                        $email
                    ]);
                    
                    $success = '管理员添加成功';
                }
            }
        } catch(PDOException $e) {
            $error = '系统错误，请稍后再试';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加管理员 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/dashboard.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
    <div class="wrapper">
        <!-- 引入侧边栏 -->
        <?php include 'includes/sidebar.php'; ?>

        <!-- 主要内容区 -->
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>添加管理员</h2>
                </div>
                <div class="header-right">
                    <a href="admin_users.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </header>

            <div class="content">
                <div class="form-container">
                    <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="username">用户名 <span class="required">*</span></label>
                            <input type="text" id="username" name="username" required>
                        </div>

                        <div class="form-group">
                            <label for="password">密码 <span class="required">*</span></label>
                            <input type="password" id="password" name="password" required>
                        </div>

                        <div class="form-group">
                            <label for="name">姓名 <span class="required">*</span></label>
                            <input type="text" id="name" name="name" required>
                        </div>

                        <div class="form-group">
                            <label for="avatar">头像</label>
                            <input type="file" id="avatar" name="avatar" accept="image/*">
                        </div>

                        <div class="form-group">
                            <label for="phone">手机号</label>
                            <input type="text" id="phone" name="phone">
                        </div>

                        <div class="form-group">
                            <label for="email">邮箱</label>
                            <input type="email" id="email" name="email">
                        </div>

                        <div class="form-group">
                            <label for="role">角色 <span class="required">*</span></label>
                            <select id="role" name="role" required>
                                <option value="2">普通管理员</option>
                                <option value="1">超级管理员</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="status">状态 <span class="required">*</span></label>
                            <select id="status" name="status" required>
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 